<template>
  <div class="exam-taking-container">
    <!-- 防作弊组件 -->
    <AntiCheating 
      v-if="examInfo.examId > 0"
      :exam-id="examInfo.examId" 
      :max-switch-count="5"
      @exceed-limit="handleExceedLimit"
      @switch-detected="handleSwitchDetected"
    />
    
    <el-card>
      <template #header>
        <div class="exam-header">
          <div class="exam-info">
            <span class="exam-title">{{ examInfo.paperName }}</span>
            <span class="exam-timer" :class="{ 'timer-warning': remainingSeconds < 300 }">
              {{ formatTime(remainingSeconds) }}
            </span>
          </div>
          <el-button type="primary" @click="handleSubmit" :disabled="submitting">
            {{ submitting ? '提交中...' : '提交考试' }}
          </el-button>
        </div>
      </template>
      
      <div v-loading="loading" element-loading-text="加载题目中..." class="exam-content-wrapper">
        <div v-if="!loading" class="exam-content">
        <!-- 题目导航 -->
        <div class="question-nav">
          <div class="nav-title">题目导航</div>
          <div class="nav-buttons">
            <el-button
              v-for="(q, index) in examInfo.questions"
              :key="q.id"
              :type="getQuestionButtonType(q.id, index)"
              size="small"
              circle
              @click="scrollToQuestion(index)"
            >
              {{ index + 1 }}
            </el-button>
          </div>
        </div>
        
        <!-- 题目列表 -->
        <div class="questions-container">
          <div
            v-for="(question, index) in examInfo.questions"
            :key="question.id"
            :id="`question-${index}`"
            class="question-item"
          >
            <div class="question-header">
              <span class="question-number">第 {{ index + 1 }} 题</span>
              <span class="question-type">{{ getQuestionTypeLabel(question.type) }}</span>
              <span class="question-score">（{{ question.score }} 分）</span>
            </div>
            
            <div class="question-content">
              <div class="question-text">{{ question.content }}</div>
              
              <!-- 单选题 -->
              <div v-if="question.type === 'single'" class="question-options">
                <el-radio-group
                  :model-value="getAnswer(question.id)"
                  @change="(val: string) => handleAnswerChange(question.id, val)"
                >
                  <el-radio
                    v-for="(option, key) in question.options"
                    :key="key"
                    :label="key"
                    class="option-item"
                  >
                    {{ key }}. {{ option }}
                  </el-radio>
                </el-radio-group>
              </div>
              
              <!-- 多选题 -->
              <div v-else-if="question.type === 'multiple'" class="question-options">
                <el-checkbox-group
                  :model-value="getMultipleAnswer(question.id)"
                  @change="(val: string[]) => handleAnswerChange(question.id, val.join(','))"
                >
                  <el-checkbox
                    v-for="(option, key) in question.options"
                    :key="key"
                    :label="key"
                    class="option-item"
                  >
                    {{ key }}. {{ option }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              
              <!-- 判断题 -->
              <div v-else-if="question.type === 'judge'" class="question-options">
                <el-radio-group
                  :model-value="getAnswer(question.id)"
                  @change="(val: string) => handleAnswerChange(question.id, val)"
                >
                  <el-radio label="true">正确</el-radio>
                  <el-radio label="false">错误</el-radio>
                </el-radio-group>
              </div>
              
              <!-- 填空题 -->
              <div v-else-if="question.type === 'fill'" class="question-input">
                <el-input
                  v-model="answers[question.id]"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入答案"
                  @blur="handleAnswerChange(question.id, answers[question.id] || '')"
                />
              </div>
              
              <!-- 简答题 -->
              <div v-else-if="question.type === 'essay'" class="question-input">
                <el-input
                  v-model="answers[question.id]"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入答案"
                  @blur="handleAnswerChange(question.id, answers[question.id] || '')"
                />
              </div>
            </div>
            
            <div v-if="saveStatus[question.id]" class="save-status">
              <el-icon><Check /></el-icon>
              <span>已保存</span>
            </div>
          </div>
        </div>
        </div>
      </div>
    </el-card>
    
    <!-- 提交确认对话框 -->
    <el-dialog
      v-model="showSubmitDialog"
      title="确认提交"
      width="400px"
    >
      <p>确定要提交考试吗？提交后将无法修改答案。</p>
      <template #footer>
        <el-button @click="showSubmitDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit">确定提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check } from '@element-plus/icons-vue'
import { startExam, getExamQuestions, saveAnswer, submitExam, type ExamInfo, type ExamQuestion } from '../../api/exam'
import AntiCheating from '../../components/AntiCheating.vue'

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const submitting = ref(false)
const showSubmitDialog = ref(false)
const examInfo = ref<ExamInfo>({
  examId: 0,
  paperName: '',
  startTime: '',
  endTime: '',
  duration: 0,
  questions: []
})

const answers = ref<Record<number, string>>({})
const saveStatus = ref<Record<number, boolean>>({})
let timer: number | null = null
const remainingSeconds = ref(0)

// 计算剩余时间
const updateRemainingTime = () => {
  if (!examInfo.value.endTime) return
  
  const endTime = new Date(examInfo.value.endTime).getTime()
  const now = Date.now()
  const diff = Math.floor((endTime - now) / 1000)
  
  if (diff <= 0) {
    remainingSeconds.value = 0
    handleTimeUp()
  } else {
    remainingSeconds.value = diff
  }
}

// 格式化时间显示
const formatTime = (seconds: number) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
}

// 获取题目类型标签
const getQuestionTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    single: '单选题',
    multiple: '多选题',
    judge: '判断题',
    fill: '填空题',
    essay: '简答题'
  }
  return typeMap[type] || type
}

// 获取答案
const getAnswer = (questionId: number): string => {
  return answers.value[questionId] || ''
}

// 获取多选题答案
const getMultipleAnswer = (questionId: number): string[] => {
  const answer = answers.value[questionId]
  if (!answer) return []
  return answer.split(',')
}

// 获取题目按钮类型
const getQuestionButtonType = (questionId: number, index: number): string => {
  if (answers.value[questionId]) {
    return 'success'
  }
  return 'default'
}

// 滚动到指定题目
const scrollToQuestion = (index: number) => {
  const element = document.getElementById(`question-${index}`)
  if (element) {
    element.scrollIntoView({ behavior: 'smooth', block: 'start' })
  }
}

// 处理答案变化
const handleAnswerChange = async (questionId: number, content: string) => {
  answers.value[questionId] = content
  
  try {
    await saveAnswer(examInfo.value.examId, questionId, content)
    saveStatus.value[questionId] = true
    
    // 3秒后隐藏保存状态
    setTimeout(() => {
      saveStatus.value[questionId] = false
    }, 3000)
  } catch (error) {
    ElMessage.error('保存答案失败')
  }
}

// 初始化考试
const initExam = async () => {
  loading.value = true
  try {
    const paperId = route.params.paperId as string
    const examIdParam = route.params.examId as string
    
    let examId: number
    
    if (examIdParam) {
      // 继续考试
      examId = parseInt(examIdParam)
    } else if (paperId) {
      // 开始新考试
      const startRes = await startExam(parseInt(paperId))
      examId = startRes.data
    } else {
      ElMessage.error('参数错误')
      router.back()
      return
    }
    
    // 获取考试题目
    const res = await getExamQuestions(examId)
    examInfo.value = res.data
    
    // 初始化答案
    examInfo.value.questions.forEach(q => {
      if (q.answer) {
        answers.value[q.id] = q.answer
      }
    })
    
    // 启动倒计时
    updateRemainingTime()
    timer = setInterval(updateRemainingTime, 1000) as unknown as number
    
  } catch (error: any) {
    ElMessage.error(error.message || '加载考试失败')
    router.back()
  } finally {
    loading.value = false
  }
}

// 时间到
const handleTimeUp = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  
  ElMessageBox.alert('考试时间已到，系统将自动提交！', '提示', {
    type: 'warning',
    confirmButtonText: '确定'
  }).then(() => {
    confirmSubmit()
  })
}

// 提交考试
const handleSubmit = () => {
  showSubmitDialog.value = true
}

// 确认提交
const confirmSubmit = async () => {
  showSubmitDialog.value = false
  submitting.value = true
  
  try {
    await submitExam(examInfo.value.examId)
    ElMessage.success('提交成功')
    
    if (timer) {
      clearInterval(timer)
      timer = null
    }
    
    router.push({
      name: 'ExamResult',
      params: { examId: examInfo.value.examId.toString() }
    })
  } catch (error: any) {
    ElMessage.error(error.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

// 处理超过切屏限制
const handleExceedLimit = () => {
  ElMessageBox.confirm('检测到您多次切换窗口，考试将被自动提交！', '警告', {
    type: 'error',
    confirmButtonText: '确定',
    showCancelButton: false
  }).then(() => {
    confirmSubmit()
  })
}

// 处理检测到切屏
const handleSwitchDetected = (count: number) => {
  // 可以选择记录日志等操作
  console.log(`检测到切屏 ${count} 次`)
}

// 离开页面提醒
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
  if (remainingSeconds.value > 0) {
    e.preventDefault()
    e.returnValue = '确定要离开吗？考试进度会自动保存。'
  }
}

onMounted(() => {
  initExam()
  window.addEventListener('beforeunload', handleBeforeUnload)
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
  window.removeEventListener('beforeunload', handleBeforeUnload)
})
</script>

<style scoped>
.exam-taking-container {
  padding: 20px;
  overflow: visible;
}

.exam-taking-container :deep(.el-card) {
  overflow: visible;
  height: auto;
  max-height: none;
}

.exam-taking-container :deep(.el-card__body) {
  overflow: visible;
  height: auto;
  max-height: none;
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exam-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.exam-title {
  font-size: 20px;
  font-weight: bold;
}

.exam-timer {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.timer-warning {
  color: #f56c6c;
}

.exam-content-wrapper {
  min-height: 400px;
}

.exam-content {
  display: flex;
  gap: 20px;
  min-height: 0;
  overflow: visible;
}

.question-nav {
  width: 200px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
  position: sticky;
  top: 20px;
  align-self: flex-start;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}

.nav-title {
  font-weight: bold;
  margin-bottom: 15px;
}

.nav-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.questions-container {
  flex: 1;
  min-width: 0;
  overflow-y: visible;
  overflow-x: hidden;
}

.question-item {
  margin-bottom: 30px;
  padding: 20px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.question-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.question-number {
  font-weight: bold;
  font-size: 16px;
}

.question-type {
  color: #409eff;
}

.question-score {
  color: #f56c6c;
}

.question-content {
  margin-bottom: 15px;
}

.question-text {
  font-size: 15px;
  line-height: 1.6;
  margin-bottom: 15px;
}

.question-options {
  padding-left: 20px;
}

.option-item {
  display: block;
  margin-bottom: 10px;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.option-item:hover {
  background-color: #f5f7fa;
}

.question-input {
  margin-top: 10px;
}

.save-status {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #67c23a;
  font-size: 12px;
  margin-top: 10px;
}

@media (max-width: 768px) {
  .exam-content {
    flex-direction: column;
  }
  
  .question-nav {
    width: 100%;
    position: static;
    max-height: none;
  }
}
</style>

